package com.jeejam.storage.service.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.jeejam.framework.base.pojo.TreePager;
import com.jeejam.framework.base.service.impl.BaseServiceImpl;
import com.jeejam.storage.dao.DepotMapper;
import com.jeejam.storage.pojo.Depot;
import com.jeejam.storage.service.DepotService;

@Service
public class DepotServiceImpl extends BaseServiceImpl implements DepotService{
	private DepotMapper depotMapper;

	@Resource
	public void setDepotMapper(DepotMapper depotMapper) {
		this.depotMapper = depotMapper;
		this.baseMapper = depotMapper;
	}

	@Override
	public List<Depot> selectRoot() {
		return depotMapper.selectRoot();
	}

	@Override
	public List<Depot> selectRootByPage(int page, int pageSize) {
		Map<String, Serializable> params = new HashMap<String, Serializable>();
		params.put("begin", (page-1)*pageSize);
		params.put("pageSize", pageSize);
		return depotMapper.selectRootByPage(params);
	}

	@Override
	public List<Depot> selectChildren(int id) {
		return depotMapper.selectChildren(id);
	}

	@Override
	public List<Depot> selectSubChildren(int parentId) {
		return depotMapper.selectSubChildren(parentId);
	}

	@Override
	public TreePager getTreePager(int currentPage, int pageSize) {
		TreePager pager = new TreePager();
		int totalGroupNum = depotMapper.countsWithRoot();
		int totalNum = baseMapper.counts();
		int totalPage = totalGroupNum % pageSize == 0 ? totalGroupNum / pageSize : totalGroupNum / pageSize + 1;
		pager.setTotalGroupNum(totalGroupNum);
		pager.setTotalNum(totalNum);
		pager.setTotalPage(totalPage);
		pager.setCurrentPage(currentPage);
		pager.setPageSize(pageSize);
		return pager;
	}

	@Override
	public int countsWithRoot() {
		return depotMapper.countsWithRoot();
	}

	@Override
	public Depot findByCode(String code) {
		return depotMapper.selectByCode(code);
	}

	@Override
	public void deleteWithChildren(int id) {
		for(Depot depot : depotMapper.selectSubChildren(id)){
			if(depot != null && depotMapper.selectSubChildren(depot.getId()) != null){
				this.deleteWithChildren(depot.getId());
				depotMapper.delete(depot.getId());
			}
		}
		depotMapper.delete(id);
	}
	
	
}
